package com.s.core.root;

import com.s.S;
import com.s.core.root.strategy.Strategy;

import java.util.List;
import java.util.stream.Collectors;

public class Ac {
    public static Strategy.STRATEGY Q_STRATEGY = null;

    private final List<CaseA> caseAList;

    private Ac() {
        caseAList = S.persistService.loadCases();

    }

    private static volatile Ac me;

    public static Ac me() {
        if (me == null) {
            synchronized (Ac.class) {
                if (me == null) {
                    me = new Ac();
                }
            }
        }
        return me;
    }

    public List<CaseA> list() {
        return caseAList.stream().filter(t -> {
            if (Q_STRATEGY == null) {
                return true;
            } else {
                return t.strategy == Q_STRATEGY;
            }
        }).collect(Collectors.toList());
    }

    public CaseA first(boolean isNext) {
        List<CaseA> cases = list();
        return isNext ? cases.get(0) : cases.get(cases.size() - 1);
    }

    public CaseA get(boolean isNext, String code, String date) {
        List<CaseA> cases = Ac.me().list();
        int index = cases.indexOf(new CaseA(code, date, null));
        if (index == -1) {
            return first(isNext);
        }
        if (isNext) {
            if (index == cases.size() - 1) {
                return cases.get(0);
            }
            return cases.get(index + 1);
        } else {
            if (index == 0) {
                return cases.get(cases.size() - 1);
            }
            return cases.get(index - 1);
        }
    }
}
